package com.example.lowbird.lowbird.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lowbird.lowbird.R;
import com.example.lowbird.lowbird.bean.LoginBean;
import com.example.lowbird.lowbird.constant.Contants;
import com.example.lowbird.lowbird.utils.DESUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.UserInterruptException;
import cn.smssdk.gui.IdentifyNumPage;
import cn.smssdk.gui.RegisterPage;
import cn.smssdk.gui.SmartVerifyPage;
import cn.smssdk.utils.SMSLog;
import okhttp3.Call;
import okhttp3.Response;

import static com.mob.tools.utils.R.getStringRes;

public class LoginActivity extends AppCompatActivity {
    private String phonenumber;
    private TextView tv_country;
    private EditText et_loginphone;
    private EditText et_loginpassword;
    String phone;

    private Context mContext;
    private TextView tv_countrycode;
    // 默认使用中国区号
    private static final String DEFAULT_COUNTRY_ID = "42";
    private String password;
    private String code;
    private Button bt_nextstep;
    private SMSeventhandler smSeventhandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mContext = this;
        SMSSDK.initSDK(this, "18c71cb44fc66", "b8d168de9f126045ddfaa7f8fdbb09b4");
        initview();


        smSeventhandler = new SMSeventhandler();

        SMSSDK.registerEventHandler(smSeventhandler);
        String[] country = SMSSDK.getCountry(DEFAULT_COUNTRY_ID);
        if (country != null) {
            Log.e("LOG", "onCreate1: " + country[1]);
            Log.e("LOG", "onCreate0: " + country[0]);

        }
        tv_countrycode.setText("+" + country[1]);
        tv_country.setText(country[0]);

        RegisterPage a;
    }

    private void initview() {
        tv_country = ((TextView) findViewById(R.id.tv_country));
        tv_countrycode = ((TextView) findViewById(R.id.tv_countrycode));

        bt_nextstep = ((Button) findViewById(R.id.bt_mynextstep));
        et_loginphone = ((EditText) findViewById(R.id.et_loginphone));

        et_loginpassword = ((EditText) findViewById(R.id.et_loginpassword));

        bt_nextstep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {



                 getcode();
            }
        });


    }

    class SMSeventhandler extends EventHandler {

        @Override
        public void afterEvent(final int event, final int result,
                               final Object data) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {


                    if (result == SMSSDK.RESULT_COMPLETE) {
                        if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                            // 请求支持国家列表

                        } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                            // 请求验证码后，跳转到验证码填写页面
                            boolean smart = (Boolean) data;
                            afterVerificationCodeRequested(smart);
                        }
                    } else {
                        if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE
                                && data != null
                                && (data instanceof UserInterruptException)) {
                            // 由于此处是开发者自己决定要中断发送的，因此什么都不用做

                            Log.e("LOG", "run: "+data.toString() );
                            return;
                        }

                        // 根据服务器返回的网络错误，给toast提示
                        try {
                            ((Throwable) data).printStackTrace();
                            Throwable throwable = (Throwable) data;

                            JSONObject object = new JSONObject(
                                    throwable.getMessage());
                            String des = object.optString("detail");
                            if (!TextUtils.isEmpty(des)) {

                                return;
                            }
                        } catch (Exception e) {
                            SMSLog.getInstance().w(e);
                        }
                        // 如果木有找到资源，默认提示
                        int resId = getStringRes(mContext,
                                "smssdk_network_error");
                        if (resId > 0) {
                            Log.e("LOG", "resId: "+resId);
                            Toast.makeText(mContext, resId, Toast.LENGTH_SHORT).show();
                        }
                    }
                }


            });


        }

    }

    /**
     * 请求验证码后，跳转到验证码填写页面
     */
    private void afterVerificationCodeRequested(boolean smart) {

        Intent intent = new Intent(mContext, LoginActivity2.class);
        phone = et_loginphone.getText().toString();
        password = et_loginpassword.getText().toString();
        code = tv_countrycode.getText().toString();
        intent.putExtra("phone", phone);
        intent.putExtra("password", password);
        intent.putExtra("code", code);


        mContext.startActivity(intent);
        finish();
    }
RegisterPage p;
    private void getcode() {

        phonenumber = et_loginphone.getText().toString().trim();
        code = tv_countrycode.getText().toString().trim();
        password = et_loginpassword.getText().toString().trim();
        checkecode(phonenumber, code);
        SMSSDK.getVerificationCode(code, phonenumber);
       // finish();

    }

    private void checkecode(String phonenumber, String code) {
        if (code.startsWith("+")) {
            code = code.substring(1);

        }

        if (TextUtils.isEmpty(phonenumber)) {
            Log.e("LOG", "checkecode: 请输入电话号码");
            return;

        }
        if (code == "86") {
            if (phonenumber.length() != 11) {
                Log.e("LOG", "checkecode: 请输入11位电话号码");
                return;
            }

        }

        String rule = "^1(3|5|7|8|4)\\d{9}";
        Pattern compile = Pattern.compile(rule);


        Matcher m = compile.matcher(phonenumber);

        if (!m.matches()) {
            Log.e("LOG", "checkecode: 请输入正确格式的电话号码");
            return;
        }


    }

    private String[] getCurrentCountry() {
        String mcc = getMCC();
        String[] country = null;
        if (!TextUtils.isEmpty(mcc)) {
            country = SMSSDK.getCountryByMCC(mcc);
        }

        if (country == null) {
            Log.w("SMSSDK", "no country found by MCC: " + mcc);
            country = SMSSDK.getCountry(DEFAULT_COUNTRY_ID);
        }
        return country;
    }

    private String getMCC() {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        // 返回当前手机注册的网络运营商所在国家的MCC+MNC. 如果没注册到网络就为空.
        String networkOperator = tm.getNetworkOperator();
        if (!TextUtils.isEmpty(networkOperator)) {
            return networkOperator;
        }

        // 返回SIM卡运营商所在国家的MCC+MNC. 5位或6位. 如果没有SIM卡返回空
        return tm.getSimOperator();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(smSeventhandler);
    }

}